package com.leosam.tvbox.mv.lucene;

import java.util.Comparator;
import java.util.HashMap;

import com.leosam.tvbox.mv.data.Vod;

final class SimilarityScoreComparator implements Comparator<Vod> {

    private String key;

    SimilarityScoreComparator(String key) {
        this.key = key;
    }

    public static int levenshteinDistance(String s1, String s2) {
        int m = s1.length();
        int n = s2.length();

        int[][] dp = new int[m + 1][n + 1];

        for (int i = 0; i <= m; i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= n; j++) {
            dp[0][j] = j;
        }

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));
                }
            }
        }

        return dp[m][n];
    }

    public static int similarityScore(String s1, String s2) {
        int distance = levenshteinDistance(s1, s2);
        int maxLength = Math.max(s1.length(), s2.length());
        if (maxLength == 0) {
            return 10000;
        } else {
            return (int) ((1.0 - ((double) distance / maxLength)) * 10000);
        }
    }

    private HashMap<String, Integer> cache = new HashMap<>();

    private int getRel(String name) {
        Integer score = cache.get(name);
        if (score != null) {
            return score;
        } else {
            score = similarityScore(name, key);
            cache.put(name, score);
            return score;
        }
    }

    @Override
    public int compare(Vod o1, Vod o2) {
        return getRel(o2.getVodName()) - getRel(o1.getVodName());
    }
}